package com.nine.controller;

import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpSession;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.annotation.RequiresAuthentication;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.nine.entity.Account;
import com.nine.entity.Users;
import com.nine.entity.UsersWithBLOBs;
import com.nine.service.AccountService;
import com.nine.service.UsersService;
import com.nine.service.impl.AccountServiceImpl;

@Controller
public class UsersController {
	@Autowired
	private UsersService usersService;

	@Autowired
	private AccountService accountService;

	// 登录
	@RequestMapping("/tolog.do")
	public String login(String username,String password,HttpSession session) {
		Subject subject = SecurityUtils.getSubject();
		UsernamePasswordToken token=new UsernamePasswordToken(username, password);
		if (token.getUsername()!=null && token.getPassword()!=null) {
			try {
				subject.login(token);
				System.out.println("登录成功。。。");
				session.setAttribute("username", username);
				return "/index.jsp";
			} catch (AuthenticationException e) {
				// TODO Auto-generated catch block
				System.out.println("登录失败。。。");
				
				return "/login.jsp";   
			}
		}
		return "/login.jsp";
		
	}

	// 显示所有用户
	@RequestMapping("showusers.do")
	@ResponseBody
	public Map<String, Object> getUsers(Integer page, Integer rows) {
		// 1.启用分页
		Page page1 = PageHelper.startPage(page, rows); // 传页码，页大小
		List<UsersWithBLOBs> list = usersService.getAllUsers();
		PageInfo<UsersWithBLOBs> pageInfo = new PageInfo<UsersWithBLOBs>(list);

		// 创建键值对集合
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("total", pageInfo.getTotal());
		map.put("rows", pageInfo.getList());
		return map;

	}

	// 添加用户
	@RequestMapping("addUsers")
	public String addUsers(UsersWithBLOBs users, @RequestParam(value = "files") CommonsMultipartFile[] files,
			HttpSession session, String vip) throws Exception {
		// 身份证照片的上传
		users.setIdcardpica(files[0].getBytes());
		users.setIdcardpicb(files[1].getBytes());
		// 推荐人用户名默认为当前登录用户
		users.setRecommender((String) session.getAttribute("username"));
		// 会员状态 1启用 0禁用
		users.setState(1);
		// 会员激活否？1启用 0停用
		users.setVipactive(0);

		// 自动创建一个账户
		Account account = new Account();
		account.setBank("会员商城银行");
		account.setHolder(users.getUsername());
		account.setMoney((float) 0);
		account.setAccountid((int) (Math.random() * 9000 + 1000));
		account.setCardnum("622848005226468" + (int) (Math.random() * 9000 + 1000));

		int flag = accountService.insertSelective(account);

		if (flag > 0) {
			users.setAccountid(account.getAccountid().toString());
		}

		// 登录密码默认为123456
		users.setLogcode("123456");
		// 注册时间
		Calendar calendar = Calendar.getInstance();
		Date date = calendar.getTime();
		users.setRegtime(date);
		users.setSavetime(date);

		int result = usersService.insert(users);
		if (result > 0) {
			if (vip != null) {
				return "m_vip/viplist.jsp";
			}
			return "m_admin/showusers.jsp";
		} else {
			return null;
		}
	}

	// 多项删除用户
	@RequiresPermissions(value = { "role:admin" }) // 进行授权
	@RequestMapping("delMoreUsers")
	@ResponseBody
	public Integer delMoreUsers(String ids) {
		if (ids != null) {
			String[] strings = ids.split(",");
			// 将字符串转换为数字数组
			Integer[] arr = new Integer[(strings.length)];
			for (int j = 0; j < strings.length; j++) {
				arr[j] = new Integer(strings[j]);

			}
			int result = usersService.delMoreUsers(arr);
			if (result == arr.length) {
				return result;
			} else {
				return null;
			}
		}
		return null;
	}

	// 通过主键查询单条
	@RequestMapping("selectUsersByPrimaryKey")
	@ResponseBody
	public UsersWithBLOBs selectByPrimaryKey(String id) {
		if (id != null) {
			UsersWithBLOBs usersWithBLOBs = usersService.selectByPrimaryKey(new Integer(id));
			return usersWithBLOBs;
		}
		return null;
	}

	// 有选择性的修改用户
	@RequestMapping("updateUsersByPrimaryKeySelective")
	public String updateByPrimaryKeySelective(UsersWithBLOBs usersWithBLOBs,
			@RequestParam(value = "files") CommonsMultipartFile[] files) {

		// 身份证照片的上传
		if (files.length > 2) {
			usersWithBLOBs.setIdcardpica(files[0].getBytes());
			usersWithBLOBs.setIdcardpicb(files[1].getBytes());
		}
		// 修改保存时间
		Calendar calendar = Calendar.getInstance();
		Date date = calendar.getTime();
		usersWithBLOBs.setSavetime(date);
		int result = usersService.updateByPrimaryKeySelective(usersWithBLOBs);
		if (result > 0) {
			return "m_admin/showusers.jsp";
		} else {
			return null;
		}
	}

	// 通过条件模糊查询用户
	@RequestMapping("getUsersByCondition")
	@ResponseBody
	public List<UsersWithBLOBs> getUsersByCondition(String username) {
		List<UsersWithBLOBs> list = usersService.getUsersByCondition("%" + username + "%");
		return list;
	}

	// 退出
	@RequestMapping("tologout.do")
	public String logout() {
		Subject subject = SecurityUtils.getSubject();
		subject.logout();
		System.out.println("退出。。。。。。。");
		return "redirect:/login.jsp";
	}

	// 根据用户名来获取本人信息
	@RequestMapping("getInfoByUname")
	@ResponseBody
	public UsersWithBLOBs getInfoByUname(HttpSession session) {
		// TODO Auto-generated method stub
		String username = (String) session.getAttribute("username");
		if (username != null) {
			return usersService.getInfoByUname(username);
		}
		return null;
	}

	// 根据用户名来查找本人密码
	@RequestMapping("getCurrentPwdByUname")
	@ResponseBody
	public Integer getCurrentPwdByUname(HttpSession session, String logCode) {
		String username = (String) session.getAttribute("username");
		if (username != null) {
			UsersWithBLOBs usersWithBLOBs = usersService.getInfoByUname(username);
			String logcode2 = usersWithBLOBs.getLogcode();
			if (logCode.equals(logcode2)) {
				return 1;
			}
		}
		return 0;
	}

	// 根据用户名修改密码
	@RequestMapping("updateCurrentlogCodeByUname")
	@ResponseBody
	public Integer updateCurrentlogCodeByUname(String logCode, HttpSession session) {
		if (logCode != null) {
			String username = (String) session.getAttribute("username");
			if (username != null) {
				return usersService.updateCurrentlogCodeByUsername(username, logCode);
			}
			return null;
		}
		return null;
	}

}
